Zepto(function () {

    // 未读消息数
    getUnreadMessage();
    // 未读消息数
    function getUnreadMessage() {

        $.ajax({
            url: baseloaction +'/mobile/user/isLogin',
            type:'post',
            dataType:'json',
            success:function (result) {
                if(result.entity==true){//如果已登录，则回调
                    getMagNum();
                }
            },
            error:function (error) {
                $.toast('系统错误，验证登录失败');
            }
        });
    }
    //下载app关闭
    $('body').on('click','.download-close',function(){
       $(this).parent().parent('div').addClass('hide');
        SetCookieOutTime('_downloadApp_',true,'s600');
    });

    //加载banner图
    getBannerList();
    //获取公告
    getNoticeList('wp-notice-txt__ul');
    //获取推荐专业
    getGroomSubjectList('subject-list');
    //获取热门直播
    getGroomDataList("AHPL", "popular-live-list");
    //获取推荐的精品课程
    getGroomDataList("IBC", "boutique-course-list");
    //获取推荐的热门课程
    getGroomDataList("IHC", "popular-course-list");
    //获取推荐的小班课
    getGroomDataList("SMALL", "small-live-list");
    //加载免费直播
    queryOpenCourseList();
    //获取推荐专业课程列表 各端未统一，暂时注掉，请勿删除
    // queryRecommendSubjectCourseList("subject-course-list");

    /**
     * 异步加载banner图
     */
    function getBannerList() {
        Zepto.ajax({
            url: baseloaction + '/mobile/index/bannerList',
            type: 'post',
            dataType: 'text',
            success: function (result) {
                Zepto("#banner").html(result);
                //幻灯片初始化配置
                new Swiper(".swiper-container-banner", {
                    autoplay: 3000,
                    loop: 0,
                    centeredSlides: 0,
                    slidesPerView: "auto",
                    pagination: ".swiper-pagination",
                    autoplayDisableOnInteraction: false
                })
            },
            error: function () {
                Zepto.toast("系统错误，加载失败");
            }
        })
    }

    /**
     * 加载公告列表
     */
    function getNoticeList(contextId){
        Zepto.ajax({
            url: baseloaction + '/mobile/index/noticeList',
            dataType: 'json',
            async: false,
            success: function (result) {
                if(result.success){
                    var articleList = result.entity;
                    var context = '';
                    if(articleList != null && articleList.length>0){
                        Zepto.each(articleList,function (index,article) {
                            context += '<li class="swiper-slide"><a href="'+baseloaction+'/mobile/article/articleInfoById?articleId='+article.dataTypeMap.id+'" class="vam ellipsis">'+article.dataTypeMap.title+'</a></li>';
                        });
                        Zepto('#'+contextId).html(context);
                        //公告滚动方法
                        upScroll('.wp-notice-txt__wrap');
                    }else {
                        context += '<li class="swiper-slide"><a href="javascript:void(0)" class="vam ellipsis">暂无推荐资讯</a></li>';
                        Zepto('#'+contextId).html(context);
                    }
                }
            }
        })
    }

    /**
     * 查询推荐专业列表
     * @param contextId 文本id
     */
    function getGroomSubjectList(contextId){
        Zepto.ajax({
            url: baseloaction + '/mobile/index/queryGroomSubjectList',
            type: 'post',
            dataType: 'json',
            success: function (result) {
                if(result.success){
                    var subjectList = result.entity;
                    var context = '';
                    Zepto.each(subjectList,function (index,subject) {
                        context = concatContext(context,subject);
                    });
                    var obj = {
                        'subjectName':'更多',
                        'imageMap':{'url':staticPath + '/front/mobile/v3/img/default/subject-recommend-default.png'},
                        'id':0
                    };
                    context = concatContext(context,obj);
                    Zepto('#'+contextId).html(context);
                    Zepto('img[data-subject]').click(function () {
                        var subjectId = Zepto(this).data('subject');
                        if(subjectId == '0'){
                            window.location = '/mobile/course/classify/index';
                        }else {
                            window.location = '/mobile/course/courseList?subjectIds='+subjectId;
                        }
                    });
                }
            }
        });
    }

    /**
     * 拼接html
     * @param context
     * @param subject
     */
    function concatContext(context,subject) {
        context += '<aside class="col-25">';
        context += '<section class="wp-in-sort-item">';
        var imgUrl = '';
        if(subject.imageMap !=null && subject.imageMap.url !=null && Zepto.trim(subject.imageMap.url)!=''){
            imgUrl = subject.imageMap.url;
        }else {
            imgUrl = staticPath + '/front/mobile/v3/img/default/in-subject-icon-default.png';
        }
        context += '<img src="'+imgUrl+'" data-subject="'+subject.id+'" width="80%" alt="'+subject.subjectName+'">';
        context += '<p><span class="c-333 fs7">'+subject.subjectName+'</span></p>';
        context += '</section>';
        context += '</aside>';
        return context;
    }

    /**
     * 获取推荐数据
     */
    function getGroomDataList(placeKey,contextId) {
        Zepto.ajax({
            url: baseloaction + '/mobile/index/queryGroomDataList',
            data: {"placeKey":placeKey},
            type: 'post',
            dataType: "text",
            success: function (result) {
                Zepto("#"+ contextId).html(result);
                lazyloadImage();
                if("AHPL"==placeKey || "SMALL"==placeKey){
                    new Swiper(".swiper-container-tuanCourse", {
                        autoplay: 0,
                        loop: 0,
                        centeredSlides: 0,
                        slidesPerView: "auto"
                    })
                }
                if(Zepto('#no-'+placeKey+'-course').val()==0){
                    if("IBC"==placeKey || "IHC"==placeKey){
                        Zepto("#"+ contextId).html(noDataContext('课程'));
                    }else {
                        Zepto('#popular-live').addClass('hide');
                        Zepto('#small-live-list').addClass('hide');
                    }
                }
            },
            error: function (error) {
                Zepto("#"+ contextId).html(noDataContext('课程'));
            }
        });
    }

    function noDataContext(message) {
        var context = '';
        context += '<div class="">';
        context += '<section class="no-data__wrap">';
        context += '<em>&nbsp;</em>';
        context += '<p>亲，暂无'+message+'数据，小编正在整理中</p>';
        context += '</section>';
        context += '</div>';
        return context;
    }

    /**
     * 加载免费直播数据列表
     */
    function queryOpenCourseList() {
        Zepto.ajax({
            url: baseloaction + '/mobile/index/queryOpenCourseList',
            type: 'post',
            dataType: "text",
            success: function (result) {
                Zepto("#open-course-list").html(result);
                if(Zepto('#no-open-course').val()==0){
                    Zepto('#open-course').addClass('hide');
                }
            },
            error: function (error) {
                var value = Zepto('#no-open-course').val();
                if(value==0 || value == null){
                    Zepto('#open-course').addClass('hide');
                }
            }
        });
    }

    /**
     * 获取推荐数据 获取推荐专业下的课程数据列表
     * @param contextId html文本id
     */
    function queryRecommendSubjectCourseList(contextId){
        Zepto.ajax({
            url: baseloaction + '/mobile/index/queryRecommendSubjectCourseList',
            type: 'get',
            dataType: 'text',
            success: function (result) {
                Zepto('#'+contextId).html(result);
                var subjectList = Zepto('div[data-subject]');
                Zepto.each(subjectList,function (index,subject) {
                    var id = Zepto(subject).data('subject');
                    var value = Zepto('#no-'+id+'-course').val();
                    if(value == 0 || value == null){
                        Zepto(subject).addClass('hide');
                    }
                });
            },
        });
    }

    Zepto('body').on('click', 'div[data-open] , span[data-open]', function () {
        var openId = Zepto(this).data('open');
        isLogin(function () {
            Zepto.ajax({
                url: baseloaction + '/mobile/open/ajax/play',
                data: {'openId': openId},
                success: function (result) {
                    if (result.success==true) {
                        if(result.status=="REPLAY"){//回放
                            if(result.playStatus=='STATUS_URL') {//URL回放方式
                                window.location = result.liveUrl;
                            }
                            if(result.playStatus=='STATUS_CODE') {//播放码回放方式
                                window.location = baseloaction + '/mobile/uc/open/playBackCode?code='+result.entity.backCode+"&playType="+result.entity.playType;
                            }
                        }
                        if(result.status=='LIVE') {//直播
                            window.location = result.liveUrl;
                        }
                    } else {
                        Zepto.toast(result.message);
                    }
                },
                error: function () {
                    Zepto.toast('系统繁忙，请稍候再试');
                }
            });
        });
    }).on('click','.bespeak-btn',function () {
        var openId = Zepto(this).data('id');
        bespeak(openId);
    }).on('click','label.icon-chazhao',function () {
        var keyword = Zepto("#search").val();
        if(keyword.trim().length==0){
            Zepto.toast('请填写课程名称');
            return false;
        }
        window.location = baseloaction + '/mobile/course/courseList?keyword='+keyword;
    }).on('keypress','#search',function(e){
        var keyword = Zepto("#search").val();
        var keycode = e.keyCode;
        if(keycode=='13' ||  keycode=='15') {
            if(keyword.trim().length==0){
                Zepto.toast('请填写关键字');
                return false;
            }
            window.location = baseloaction + '/mobile/globalSearch/globalSearchIndex?keyword='+keyword;
        }
    });

    /**
     * 预约免费直播
     * @param openId 免费直播ID
     */
    function bespeak(openId) {
        isLogin(function () {
            Zepto.ajax({
                url:baseloaction +'/mobile/uc/open/bespeakOpen',
                type:'post',
                dataType:'json',
                data:{
                    'openId':openId
                },
                success:function (result) {
                    Zepto.toast(result.message);
                    Zepto('span.bespeak-btn').text('已预约');
                },
                error:function (error) {
                    Zepto.toast('系统错误，免费直播预约失败');
                }
            });
        });
    }

    //首页头部交互效果
    function inHeadFn() {
        var ele = Zepto('header.wp-in-header'),
            sFn = function () {
                var t = Zepto('.content').scrollTop();
                if(t > 100) {
                    ele.addClass('bg-gradient').removeClass('bg-transparent')
                } else {
                    ele.addClass('bg-transparent').removeClass('bg-gradient')
                }
            };
        document.querySelector('.content').addEventListener('scroll', function () {
            sFn()
        })
    }

    /*模块加载完成后进行业务操作*/
    Zepto(function () {

        //幻灯片初始化配置
        new Swiper(".swiper-container-banner", {
            autoplay: 3000,
            loop: 0,
            centeredSlides: 0,
            slidesPerView: "auto",
            pagination: ".swiper-pagination",
            autoplayDisableOnInteraction: false
        })
        //划算左右滑动
        new Swiper(".swiper-container-tuanCourse", {
            autoplay: 0,
            loop: 0,
            centeredSlides: 0,
            slidesPerView: "auto"
        })
        //首页头部交互效果
        inHeadFn()
        //公告滚动方法
        upScroll('.wp-notice-txt__wrap')
    })

    /*if(isWeiXin()){
        //初始化微信分享
        initializeWxShare({
            title:"268教育软件",
            desc:"268教育集团成立于2013年4月，隶属于北京易知路科技有限公司，是一家专注在线教育产品研究、开发以及在线教育解决方案一站式服务的高科技企业",
            url:window.location.href,
            img:logourl
        });
    }*/

    //检查是否展示app下载
    checkNotDownloaded();

    function checkNotDownloaded(){
       var downloadApp = getCookie('_downloadApp_');
        if(downloadApp){
            $('.in-appDownload__wrap').addClass('hide');
        }else{
            $('.in-appDownload__wrap').removeClass('hide');
        }
    }

    //禁止ios浏览器页面上下滚动 (橡皮筋效果)
    iosTrouchFn(document.querySelector('.content'))

    function getMagNum(){
        Zepto.ajax({
            url: baseloaction + '/mobile/uc/op/affiche/countReceiveAffiche',
            type: 'post',
            success: function (response) {
                if (response.success) {
                    var count = response.entity;
                    if (count&&count!=0) {
                        Zepto('#unread-message-count').text(count).removeClass('hide');
                    } else {
                        Zepto('#unread-message-count').addClass('hide');
                    }
                }
            },
            error: function () {
                Zepto('#unread-message-count').addClass('hide');
            }
        });
    }

    $("body").on('click','.openBanner',function(){
        if($(this).data("jump")==2){
            window.open($(this).data("soure"),"_blank")
        }else{
            window.location.href=$(this).data("soure");
        }

        //计算uv pv
        $.ajax({
            url: baseloaction + '/mobile/index/savePageView',
            type: 'post',
            dataType: "json",
        })

    });
});
